﻿using NCP.Core.DataUtil;
using NCP.Core.IoC;
using NCP.Model;
using SqlSugar;
using SqlSugar.Extensions;
using System;
using System.Collections.Generic;

namespace NCP.Service
{

    public class RoleService : BaseService<Role>, IService
    {
        public RoleService()
        {
            _client = DbHelper.GetSqlSugarClient();
        }

        public List<Permission> GetPmsByRoleId(string roleId)
        {
            _client.MappingColumns.Add("RoleId", "RoleId", "Permission");
            List<Permission> pmsList = _client.Ado.SqlQuery<Permission>("select p.*,r.RoleId from Permission p left join PmsInRole r on p.Id=r.PmsId and r.RoleId=@RoleId", new SugarParameter("@RoleId", string.IsNullOrEmpty(roleId) ? 0 : roleId.ObjToInt()));
            return pmsList;
        }

        public bool GrantRights(List<PmsInRole> pmsinRoleList)
        {
            try
            {
                _client.Ado.BeginTran();
                _client.Ado.ExecuteCommand("delete from Pmsinrole where RoleId=@RoleId", new SugarParameter("@RoleId", pmsinRoleList[0].RoleId));
                _client.Insertable<PmsInRole>(pmsinRoleList).ExecuteCommand();
                _client.Ado.CommitTran();
                return true;
            }
            catch (Exception ex)
            {
                _client.Ado.RollbackTran();
            }
            return false;
        }

        public List<Role> GetRolesById(string staffCode)
        {
            List<Role> roleList = _client.Ado.SqlQuery<Role>(@"select r.*,
            case when t.RoleId !=0 then '1' else '0' end as IsChecked
            from role r
            left join (select * from MemberInRole u where u.Code = @StaffCode) t
            on r.id = t.roleid where RoleCode!='Normal'", new SugarParameter("@StaffCode", staffCode));
            return roleList;
        }

        public bool GrantRoles(List<MemberInRole> userInRoles)
        {
            try
            {
                _client.Ado.BeginTran();
                _client.Ado.ExecuteCommand("delete from MemberInRole where Code=@StaffCode", new SugarParameter("@StaffCode", userInRoles[0].Code));
                _client.Insertable<MemberInRole>(userInRoles).ExecuteCommand();
                _client.Ado.CommitTran();
                return true;
            }
            catch (Exception ex)
            {
                _client.Ado.RollbackTran();
            }
            return false;
        }

        public bool RemoveUserRole(string staffCode, string roleId)
        {
            string sqlstr = string.Format("delete from MemberInRole where Code='{0}' and RoleId='{1}'", staffCode, roleId);
            return _client.Ado.ExecuteCommand(sqlstr) > 0;
        }
    }
}
